var PPurchase = {
    u: '/outRepositoryDetail'
    , uList: '/outRepositoryDetail/list'
    , uEdit: '/outRepositoryDetail/add',
    editIndex: -1
};

$.extend($.fn.datagrid.defaults.editors, {
    house: {
        init: function (container, options) {
            return $('<div style="text-align: center">编辑</div>').appendTo(container);
        },
        destroy: function (target) {
            $(target).remove();
        },
        getValue: function (target) {
            var rows = PPurchase.dtable.datagrid("getRows");
            var house = rows[PPurchase.editIndex].house;
            return house;
        },
        setValue: function (target, value) {
        },
        resize: function (target, width) {
            $(target).click(function () {
                var rows = PPurchase.dtable.datagrid("getRows");
                var skuId = rows[PPurchase.editIndex].skusId;
                var house = rows[PPurchase.editIndex].house;
                var href = "/wWearhouse/treeGrid?skuId=" + skuId + "&house=" + house + "&type=1";//type 0出库 1入库
                var $dg = $yd.win.create('仓库/库位', href);
                $dg.width = "450px;";
                $dg.height = "520px;";
                $dg.open(function (that, $win) {

                }, function (that, $win) {
                    var data = KW.getResult();
                    PPurchase.dtable.datagrid('updateRow',{
                        index: PPurchase.editIndex,
                        row: {
                            house: data
                        }
                    });

                    that.close();
                });
            });

            $(target)._outerWidth(width);
        }
    }
});

PPurchase.dg = function () {
    PPurchase.supplierArr = [];
    $.ajax({
        type: "POST",
        url: "/wRelativeUnit/supplier/list",
        dataType: "json",
        success: function (data) {
            PPurchase.supplierArr = data;
        }
    });
    PPurchase.wearhouse = [];
    $.ajax({
        type: "POST",
        url: "/wWearhouse/getRepositoryList",
        dataType: "json",
        success: function (data) {
            PPurchase.wearhouse = data;
        }
    });


    $.ajax({
        type: "POST",
        url: "/sysDict/materiel_MU",
        dataType: "json",
        success: function (data) {
            PPurchase.unitArr = data;
        }
    });
    
    PPurchase.positionArr = [];
    $.ajax({
        type: "POST",
        url: "/wPosition/getPositionList",
        dataType: "json",
        success: function (data) {
            PPurchase.positionArr = data;
        }
    });
    PPurchase.dtable = $('#outRepository_table');
    PPurchase.dtable.datagrid({
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: false,
        columns: [[
            {field: 'skusId', checkbox: true},//规格id
            {field: 'goodsName', title: '商品名称', width: 150},
            {field: 'goodsId', title: '商品ID', width: 80, hidden: true},
            {field: 'skus', title: '规格', width: 200},
            {field: 'code', title: '商品编号', width: 80},
            {field: 'unit', title: '单位', width: 80, formatter: function (value, row, index) {
                for (var i = 0; i < PPurchase.unitArr.length; i++) {
                    if (value == PPurchase.unitArr[i].id) {
                        return PPurchase.unitArr[i].text;
                    }
                }
                return value;
            }},
            {
                field: 'ralativeId', title: '<span style="color:blue">供应商</span><span style="color:red">*</span>', width: 150, editor: {
                type: 'combobox', options: {
                    required: true,
                    editable: false,
                    valueField: 'id',
                    textField: 'name',
                    url: "/wRelativeUnit/supplier/list"
                }
            }, formatter: function (value, row, index) {
                for (var i = 0; i < PPurchase.supplierArr.length; i++) {
                    if (value == PPurchase.supplierArr[i].id) {
                        return PPurchase.supplierArr[i].name;
                    }
                }
                return value;
            }
            },
            {field: 'house', title: '仓库/库位', width: 120, editor:{type:'house'}, formatter: function () {
                if(PPurchase.isEmpty(value)) {
                    return "";
                }
                var arr = value.split("_");
                return  arr[3] + "：" +arr[1];
            }},
            {field: 'batchCode', title: '<span style="color:blue">批号</span>', width: 80, editor: {type: 'text'}},
            // { field: 'wearhouseId', title: '<span style="color:blue">仓库</span><span style="color:red">*</span>', width: 150, editor: {
            //     type: 'combobox', options: {
            //         required: true,
            //         editable: false,
            //         valueField: 'id',
            //         textField: 'name',
            //         url: "/wWearhouse/getRepositoryList"
            //     }
            // }, formatter: function (value, row, index) {
            //     for (var i = 0; i < PPurchase.wearhouse.length; i++) {
            //         if (value == PPurchase.wearhouse[i].id) {
            //             return PPurchase.wearhouse[i].name;
            //         }
            //     }
            //     return value;
            // }
            // },
            // {
            //     field: 'positionId', title: '<span style="color:blue">库位</span><span style="color:red">*</span>', width: 150, editor: {
            //     type: 'combobox', options: {
            //         required: true,
            //         editable: false,
            //         valueField: 'id',
            //         textField: 'name',
            //         url: "/wPosition/getPositionList"
            //     }
            // }, formatter: function (value, row, index) {
            //     for (var i = 0; i < PPurchase.positionArr.length; i++) {
            //         if (value == PPurchase.positionArr[i].id) {
            //             return PPurchase.positionArr[i].name;
            //         }
            //     }
            //     return value;
            // }
            // },

            {
                field: 'count',
                title: '<span style="color:blue">数量</span><span style="color:red">*</span>',
                width: 80,
                editor: {type: 'numberbox', options: {required: true, min: 1, precision: 0}}
            },
            {
                field: 'surplusCount',
                title: '当前仓库剩余数量',
                width: 80,
            },


           


            {field: 'remark', title: '<span style="color:blue">备注</span>', width: 80, editor: {type: 'text', options: {required: false}}},
        ]],
        onClickCell: function (index, field) {
            if (PPurchase.editIndex != index) {
                if (PPurchase.editIndex > -1) {
                    PPurchase.dtable.datagrid('endEdit', PPurchase.editIndex);
                }
                PPurchase.editIndex = index;
            }
            if (field == "ralativeId" || field == "batchCode" || field == "amount" || field == "amountActual" || field == "count" || field == "payStatus" || field == "remark") {
                PPurchase.dtable.datagrid('beginEdit', index);
            }
        },
        onEndEdit: function (index, row, changes) {
            var surPlusCountData = 0;
            a();
            function a() {
                var value = row['house']

                if (value != null && value != ''){
                var positionId = value.split('_')[0];
                    var wearhouseId = value.split('_')[2];
                $.ajax({
                    url:'/repositoryCount/getSurplusCount?skuId='+row['skusId']+'&wearhouseId='+wearhouseId+'&positionId='+positionId,
                    type:'GET',
                    async:false,
                    success:function (data) {
                        surPlusCountData=data;
                    }
                });
                }


            }
            if (changes) {
                PPurchase.dtable.datagrid('updateRow', {
                    index: index,
                    row: {
                        surplusCount: surPlusCountData
                    }
                });

            }
        }
    }).parent().keyup(function (event) {
        if (event.keyCode == 13) {
            PPurchase.dtable.datagrid('acceptChanges').datagrid('clearSelections');
        }
    });

    PPurchase.dtable.datagrid('enableCellEditing');
};

PPurchase.refresh = function () {
    window.location.reload();
};

PPurchase.plus = function() {
    var href = "/mMateriel/tree";
    var $dg = $yd.win.create('商品', href);
    $dg.width = "450px;";
    $dg.height = "520px;";
    $dg.open(function (that, $win) {

        }, function (that, $win) {
            var data = GoodsTree.getChecked();
            if(data.length == 0) {
                that.close();
                return;
            }

            var rows = PPurchase.dtable.datagrid("getData").rows;
            for(var i=0; i<data.length; i++) {
                var surPlusCountData;
                if (!isExist(rows, data[i].skusId)) {
                  // a();
                    function a() {

                        $.ajax({
                            url:'/repositoryCount/getSurplusCount?skuId='+data[i].skusId+'&wearhouseId='+data[i].wearhouseId,
                            type:'GET',
                            async:false,
                            success:function (data) {
                                surPlusCountData=data;
                            }
                        });
                    }
                    PPurchase.dtable.datagrid('appendRow', {
                        skusId: data[i].skusId,
                        goodsName: data[i].goodsName,
                        goodsId: data[i].goodsId,
                        skus: data[i].skusName,
                        code: data[i].code,
                        unit: data[i].unit,
                        ralativeId: data[i].ralativeId,
                        wearhouseId: data[i].wearhouseId,
                        positionId: data[i].positionId,
                        surplusCount:surPlusCountData,


                    }).datagrid('clearSelections');
                }
                // function a() {
                //     $.ajax({
                //         url:'getSurplusCount?skuId='+data[i].skusId+'&wearhouseId='+data[i].wearhouseId,
                //         type:'GET',
                //         success:function (data) {
                //             surPlusCount:data;
                //         }
                //     });
                // }
                
                
            }
            that.close();
        }
    );

    function isExist(rows, skusId) {
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].skusId == skusId) {
                return true;
            }
        }
        return false;
    }
};

Array.prototype.contains = function ( needle ) {
    for (var i in this) {
        if (this[i] == needle) return true;
    }
    return false;
};

//删除
PPurchase.remove = function () {
    var sels = PPurchase.dtable.datagrid('getChecked');
    if (sels.length == 0) {
        $yd.alert('请选中记录');
        return;
    }
    var ids = [];
    $.each(sels, function (i, n) {
        ids.push(n['skusId']);
    });

    $.each(ids, function (i,n) {
        var rows = PPurchase.dtable.datagrid('getRows');
        for(var ii=0; ii<rows.length; ii++) {
            if(rows[ii].skusId == n) {
                PPurchase.dtable.datagrid('deleteRow', ii);
                break;
            }
        }
    });
};

PPurchase.isEmpty = function(value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
}
PPurchase.save0 = function() {
    PPurchase.save(0);
}
PPurchase.save1 = function() {
    PPurchase.save(1);
}
PPurchase.save = function(type) {
    //结束编辑状态
    if (PPurchase.editIndex != undefined && PPurchase.editIndex != -1) {
        PPurchase.dtable.datagrid('endEdit', PPurchase.editIndex);
    }

    $('#myForm').form('submit', {
        url: PPurchase.uEdit,
        onSubmit: function () {
            var isValid = $(this).form('validate');//只能校验处于编辑状态的栏位
            if (!isValid) {
                return isValid;
            }

            //校验数据
            var rows = PPurchase.dtable.datagrid("getRows");
            if (rows.length == 0) {
                $yd.alert("请添加商品");
                return false;
            }

            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];

                if (PPurchase.isEmpty(row.ralativeId)) {
                    $yd.alert("第" + (i + 1) + "行：供应商不能为空");
                    return false;
                }
                if (PPurchase.isEmpty(row.house)) {
                    $yd.alert("第" + (i + 1) + "行：仓库不能为空");
                    return false;
                }
                if (PPurchase.isEmpty(row.count)) {
                    $yd.alert("第" + (i + 1) + "行：数量不能为空");
                    return false;
                }

                if (row.count>row.surplusCount) {
                    $yd.alert("第" + (i + 1) + "行：数量已超过最大库存");
                    return false;
                }
            }

            //封装数据
            $("#type").val(type);
            $("#goods").val(JSON.stringify(rows));
            return isValid;
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if(d.code == 0) {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            }else {
                $yd.alert(d.message, function () {
                    // window.location.reload();
                });
            }
        }
    });
};

// 处理按钮
PPurchase.btn = function () {
    var sb = new $yd.SearchBtn($(PPurchase.obtn));
    // sb.create('save', '生单入库', PPurchase.save1);
    sb.create('save green', '保存出库单', PPurchase.save0);
    sb.create('remove', '删除', PPurchase.remove);
    sb.create('refresh', '刷新', PPurchase.refresh);
    sb.create('plus', '新增', PPurchase.plus);
};

$(function () {
    PPurchase.obtn = '#outRepository_btn';

    PPurchase.dg(); // 数据表格
    PPurchase.btn(); // 初始化按钮

    //默认值
    $("input[name='outRepositoryType']").combobox({
        url: "/sysDict/outRepository", //outRepository
        panelHeight:'auto',
        required:true,
        valueField:'id',
        textField:'text',
        onLoadSuccess: function () {
            var d = $(this).combobox("getData");
            $(this).combobox("setValue", d[0].value);
        }
    });

    $("input[name='orderTime']").datebox({
        required:true,
        editable:false,
        value:new Date().getFullYear()+"-" + (new Date().getMonth()+1) + "-" + new Date().getDate()
    });
});